package tcentcloudutil

import (
	"fmt"
	"shop/common/log"
	"shop/config"
	"strconv"

	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/regions"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111" // 引入sms
)

var smsCli *sms.Client

func InitSmsClient() {
	credential := common.NewCredential(
		config.Conf.TencentCloudSecretId,
		config.Conf.TencentCloudSecretKey,
	)
	client, err := sms.NewClient(credential, regions.Guangzhou, profile.NewClientProfile())
	if err != nil {
		log.Errorf("fail to sms.NewClient(), err:%v", err)
	}
	smsCli = client
}

// SendSmsVerifyCode 发送短信验证码, ttl: 多少秒后过期
func SendSmsVerifyCode(phone, code string, ttl int64) bool {
	request := sms.NewSendSmsRequest()
	request.SmsSdkAppId = common.StringPtr(config.Conf.TencentCloudSmsAppId)
	/* 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名，签名信息可登录 [短信控制台] 查看 */
	request.SignName = common.StringPtr(config.Conf.TencentCloudSmsSignName)
	request.TemplateParamSet = common.StringPtrs([]string{code, strconv.FormatInt(ttl, 10)})
	request.TemplateId = common.StringPtr(config.Conf.TencentCloudSmsTemplateId)
	/* 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]，最多不要超过200个手机号*/
	request.PhoneNumberSet = common.StringPtrs([]string{"+86" + phone})

	resp, err := smsCli.SendSms(request)
	if err != nil {
		fmt.Printf("fail to SendSms, err:%v", err)
		return false
	}
	log.Debugf("发送短信验证码, resp:%s", resp.ToJsonString())
	return resp.Response != nil && resp.Response.SendStatusSet != nil && len(resp.Response.SendStatusSet) == 1 && *resp.Response.SendStatusSet[0].Code == "Ok"
}
